package com.linkage.jz.bankruptcy.activity.Project;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.linkage.jz.bankruptcy.R;
import com.linkage.jz.bankruptcy.adapter.FullyGridLayoutManager;
import com.linkage.jz.bankruptcy.base.BaseCreateActivity;
import com.linkage.jz.bankruptcy.bean.ProTalkDetail;
import com.linkage.jz.bankruptcy.bean.TaskAtta;
import com.linkage.jz.bankruptcy.event.RefreshEvent;
import com.linkage.jz.bankruptcy.net.BaseSubscriber;
import com.linkage.jz.bankruptcy.net.Network;
import com.linkage.jz.bankruptcy.utils.FileUtil;
import com.linkage.jz.bankruptcy.widget.CommonPromptDialog;
import com.linkage.seapeak.activity.vote.CreditorMultiSelectActivity;
import com.linkage.seapeak.pojo.UploadImage;
import com.linkage.seapeak.utils.ToastUtil;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import rx.Observable;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * @author AFAP
 * 创建话题
 */
public class CreateProTalkActivity extends BaseCreateActivity implements OnClickListener {
    private static final String TAG = CreateProTalkActivity.class.getSimpleName();
    public static final String KEY_ACTION = "action";
    public static final String KEY_TALK = "talk";


    private String mProjectID;
    private ProTalkDetail mProTalkDetail;


    private RecyclerView mImgRecyclerView;
    private List<UploadImage> mImgList = new ArrayList<>();
    private GridImagesAdapter mImgAdapter;

    private LinearLayout ll_talk_jionuser1,ll_talk_looker1,ll_talk_jionuser2,ll_talk_looker2;
    private EditText et_subject, et_desc;

    private TextView tv_talk_looker,tv_talk_jionuser;



    @Override
    public void initData() {
    }

    @Override
    public void setListener() {
    }

    @Override
    public void initTitle() {
    }

    @Override
    public void initView() {

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setContentView(R.layout.activity_create_pro_talk);
        super.onCreate(savedInstanceState);

        if (TextUtils.equals(getIntent().getStringExtra(KEY_ACTION), "edit")) {
            mProTalkDetail = (ProTalkDetail) getIntent().getSerializableExtra(KEY_TALK);
            mProjectID = mProTalkDetail.getBankruptcyProjectId();
        } else {
            mProjectID = getIntent().getStringExtra(KEY_PROJECTID);
        }
        initViews();
        if (mProTalkDetail != null) {
            titlebar_title.setText("编辑话题");
            ll_talk_jionuser1.setVisibility(View.GONE);
            ll_talk_looker1.setVisibility(View.GONE);
            ll_talk_jionuser2.setVisibility(View.GONE);
            ll_talk_looker2.setVisibility(View.GONE);


        } else {
            titlebar_title.setText("发起话题");
        }

        titlebar_menu_text.setOnClickListener(this);
    }

    private CommonPromptDialog mPromptDialog;
    @Override
    public void onBackPressed() {
        //super.onBackPressed();
        mPromptDialog = new CommonPromptDialog(this,CommonPromptDialog.TYPE_TIPS);
        mPromptDialog.setContent("放弃编辑？");
        mPromptDialog.setPositiveClickListener("是", new OnClickListener() {
            @Override
            public void onClick(View view) {
                CreateProTalkActivity.super.onBackPressed();
            }
        });
        mPromptDialog.setNegativeClickListener("否", new OnClickListener() {
            @Override
            public void onClick(View view) {
                mPromptDialog.dismiss();
            }
        });
        mPromptDialog.show();
    }
    public void initViews() {
        titlebar_back.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                onBackPressed();
            }
        });
        titlebar_menu_text.setVisibility(View.VISIBLE);
        et_subject = findViewById(R.id.et_subject);
        et_desc = findViewById(R.id.et_desc);
        ll_talk_looker1 = findViewById(R.id.ll_talk_looker1);
        ll_talk_jionuser1 = findViewById(R.id.ll_talk_jionuser1);
        ll_talk_looker2 = findViewById(R.id.ll_talk_looker2);
        ll_talk_jionuser2 = findViewById(R.id.ll_talk_jionuser2);
        tv_talk_looker = findViewById(R.id.tv_talk_looker);
        tv_talk_jionuser = findViewById(R.id.tv_talk_jionuser);

        mImgRecyclerView = findViewById(R.id.recycler_imgs);
        FullyGridLayoutManager manager = new FullyGridLayoutManager(this, 4, GridLayoutManager.VERTICAL, false);
        mImgRecyclerView.setLayoutManager(manager);
        mImgAdapter = new GridImagesAdapter(this, TYPE_EDIT);
        mImgAdapter.setList(mImgList);
        mImgRecyclerView.setAdapter(mImgAdapter);

        if (mProTalkDetail != null) {
            et_subject.setText(mProTalkDetail.getSubjectTitle());
            et_desc.setText(mProTalkDetail.getSubjectDescribe());

            // 参与人员和可浏览人员
//            tv_task_missonexer.setText(mProTalkDetail.getUser().getUsername());

            for (int i = 0; i < mProTalkDetail.getAttachments().size(); i++) {
                TaskAtta atta = mProTalkDetail.getAttachments().get(i);
                JSONObject obj = new JSONObject();
                try {
                    obj.putOpt("filename", atta.getAttachmentName());
                    obj.putOpt("filepath", atta.getAttachmentDownloadAddress());
                    obj.putOpt("filesize", atta.getAttachmentSize());
                    obj.putOpt("loadUrl", atta.getAttachmentWatermarkAddress());
                    mImgList.add(new Gson().fromJson(obj.toString(), UploadImage.class));
                    BaseCreateActivity.sorFiles(mImgList, true);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    private String seluserId_look;
    private String seluserId_jion;
    public final int REQUEST_SEL_LOOK_ACTIVITY = 10001;
    public final int REQUEST_SEL_JOIN_ACTIVITY = 10002;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
        super.onActivityResult(requestCode, resultCode, intent);
        switch (requestCode) {
            case REQUEST_SEL_JOIN_ACTIVITY:
                if (resultCode == RESULT_OK) {
                    if (intent != null) {
                        seluserId_jion = intent.getStringExtra("seluserId");
                        tv_talk_jionuser.setText(intent.getStringExtra("seluserName"));
                    }
                }
                break;
            case REQUEST_SEL_LOOK_ACTIVITY:
                if (resultCode == RESULT_OK) {
                    if (intent != null) {
                        seluserId_look = intent.getStringExtra("seluserId");
                        tv_talk_looker.setText(intent.getStringExtra("seluserName"));
                    }
                }
                break;
        }
    }

    @Override
    public void onClick(View view) {
        Intent intent;
        switch (view.getId()) {
            case R.id.titlebar_menu_text:
                saveData();
                break;
            case R.id.tv_talk_jionuser:

//                intent = new Intent(CreateProTalkActivity.this, ManagerSelListActivity.class);
                intent = new Intent(CreateProTalkActivity.this, CreditorMultiSelectActivity.class);
                intent.putExtra("projectId", mProjectID);
                intent.putExtra("type", "1");
                intent.putExtra("form","sysuserid");
                startActivityForResult(intent, REQUEST_SEL_JOIN_ACTIVITY);
                break;
            case R.id.tv_talk_looker:
//                intent = new Intent(CreateProTalkActivity.this, ManagerSelListActivity.class);
                intent = new Intent(CreateProTalkActivity.this, CreditorMultiSelectActivity.class);
                intent.putExtra("projectId", mProjectID);
                intent.putExtra("form","sysuserid");
                intent.putExtra("type", "1");
                startActivityForResult(intent, REQUEST_SEL_LOOK_ACTIVITY);
                break;

            default:
                break;
        }
    }

    public void saveData() {
        String str_subject = et_subject.getText().toString();
        if (TextUtils.isEmpty(str_subject)) {
//            ToastUtil.showShort("话题名称不能为空");
            showToast("话题名称不能为空", ToastUtil.TOAST_TYPE.WARNING);
            return;
        }
        if (TextUtils.isEmpty(seluserId_jion) && mProTalkDetail == null) {
//            ToastUtil.showShort("请选择参与人员");
            showToast("请选择参与人员", com.linkage.seapeak.utils.ToastUtil.TOAST_TYPE.WARNING);
            return;
        }

        String str_desc = et_desc.getText().toString();

        JSONArray fileArr = new JSONArray();
//        for (int i = 1; i < mImgList.size(); i++) {
//            fileArr.put(mImgList.get(i).parse2JSON());
//        }

        for (int i = 0; i < mImgList.size(); i++) {
            if (TextUtils.equals(mImgList.get(i).getFilename(), NAME_ADD)) {
                continue;
            }
            JSONObject obj = new JSONObject();
            try {
                if (FileUtil.isImage(mImgList.get(i).getFilename())) {
                    obj.putOpt("filename", "相关附件" + (i + 1) + ".jpg");
                } else {
                    obj.putOpt("filename", mImgList.get(i).getFilename());
                }
                obj.putOpt("filepath", mImgList.get(i).getFilepath());
                obj.putOpt("filesize", mImgList.get(i).getFilesize());
                obj.putOpt("loadUrl", mImgList.get(i).getLoadUrl());
                fileArr.put(obj);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        mShapeLoadingDialog.setLoadingText("提交信息中...");
        mShapeLoadingDialog.setCanceledOnTouchOutside(false);
        mShapeLoadingDialog.show();
        Observable<JsonObject> observable;
        if (mProTalkDetail != null) {
            observable = Network
                    .getAPIService()
                    // TODO 参数待完善
                    .editTalk(getUserToken(), mProjectID, mProTalkDetail.getId(), str_subject, str_desc,  fileArr.toString());
        } else {
            observable = Network
                    .getAPIService()
                    .sendTalk(getUserToken(), mProjectID, str_subject, str_desc, 1, seluserId_jion, seluserId_look,
                            fileArr.toString());
        }

        observable
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseSubscriber<JsonObject>() {
                    @Override
                    public void onNext(JsonObject json) {
                        mShapeLoadingDialog.dismiss();
                        int code = json.get("code").getAsInt();
                        if (code != 0) {
                            super.onNext(json);
                            return;
                        }
                        RefreshEvent event = new RefreshEvent();
                        event.setType(RefreshEvent.TYPE_TALK);
                        EventBus.getDefault().post(event);
                        showToast("提交成功", ToastUtil.TOAST_TYPE.SUCCESS);
                        finish();
                    }

                    @Override
                    public void onCompleted() {
                        super.onCompleted();
                    }

                    @Override
                    public void onError(Throwable e) {
                        mShapeLoadingDialog.dismiss();
                        super.onError(e);
                    }
                });
    }
}

